<template>
    <div>
        <div class="city-search">
            <input class="search-input" type="text" placeholder="输入城市名称或拼音"
                   v-model="keyword">
        </div>

        <div class="search-content" ref="wrapper" v-show="keyword">
            <ul>
                <li class="search-item border-bottom"
                    v-for="item of list"
                    :key="item.id"
                    @click="changeCity(item.name)" >
                {{item.name}}
                </li>
                <li class="search-item border-bottom" v-show="hasNoData">
                没有找到匹配数据
                </li>
            </ul>
        </div>

    </div>
</template>

<script>
import Bscroll from 'better-scroll'
// import { mapMutations } from 'vuex'

export default {
  name: 'CitySearch',
  props: {
    cities: {}
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  methods: {
    changeCity (newCity) {
    //   console.log(newCity)
      this.$store.dispatch('actionsChangeCity', newCity)
      this.$router.push('./')
    }
  },
  mounted () {
    this.myscroll = new Bscroll(this.$refs.wrapper, {
      click: true,
      observeDOM: true
    })
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword && this.list.length !== 0) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style scoped>
.city-search{
    height: 42px;
    line-height: 42px;
    text-align: center;
    background: rgb(192, 141, 250);
    /* margin-bottom: 0.5px; */
}
.search-input{
    box-sizing: border-box;
    text-align: center;
    width: 95%;
    height: 80%;
    line-height: 80%;
    border-radius: 7px;
    color: #666;
    padding: 0 5px;
}

.search-content{
    z-index: 99999;
    background: #eee;
    overflow: hidden;
    position: absolute;
    top: 82px;
    bottom: 0;
    left: 0;
    width: 100%;
}

.search-item{
    line-height: 20px;
    padding-left: 10px;
    color: #666;
    background: #fff;
    margin-bottom: 2px;
}

</style>
